<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class OrderStats extends Stats {

    private $Db = false;
    private $QueryMonth = false;

    public function __construct($QueryMonth) {
        $this->Db = Db::get_instance();
        $this->QueryMonth = $QueryMonth;
    }

    public function getSaleData() {
        $ret = $this->Db->query("select DATE_FORMAT(create_date,'%m-%d') AS m,SUM(amount) AS amount from fac_consumer_order WHERE `order_state` = '已完成' AND DATE_FORMAT(create_date,'%Y-%m') = '$this->QueryMonth' GROUP BY `m`;");
        $r1 = array();
        $r2 = array();
        foreach ($ret as $r) {
            $r1[] = $r['m'];
            $r2[] = $r['amount'];
        }
        $this->echoJson(array(
            'a' => $r1,
            'b' => $r2
        ));
    }

    public function getCustomPercent() {
        $ret = $this->Db->query("select (SELECT customer_name FROM `fac_customer` WHERE `fac_customer`.customer_id = fac_consumer_order.customer_id) AS customer_name,SUM(amount) / (select SUM(amount) from fac_consumer_order WHERE DATE_FORMAT(create_date,'%Y-%m') = '$this->QueryMonth' AND `order_state` = '已完成') * 100 AS percent from fac_consumer_order WHERE DATE_FORMAT(create_date,'%Y-%m') = '$this->QueryMonth' AND `order_state` = '已完成' GROUP BY `customer_id` LIMIT 10;");
        $r1 = array();
        foreach ($ret as $r) {
            $r1[] = array($r['customer_name'], (float) $r['percent']);
        }
        $this->echoJson(array(
            'a' => $r1
        ));
    }

    public function getProductPercent() {
        $ret = $this->Db->query("select fm.product_model,fi.number / (SELECT SUM(number) FROM `fac_consumer_order_item` WHERE DATE_FORMAT(create_date,'%Y-%m') = '$this->QueryMonth') * 100 AS percent from `fac_consumer_order_item` fi
LEFT JOIN `fac_consumer_order` fo on `fo`.consumer_order_id = fi.consumer_order_id
LEFT JOIN `fac_product_mess` fm on fm.product_id = fi.product_id
WHERE DATE_FORMAT(create_date,'%Y-%m') = '$this->QueryMonth' AND `order_state` = '已完成'
GROUP BY fm.product_id LIMIT 10");
        $r1 = array();
        foreach ($ret as $r) {
            $r1[] = array($r['product_model'], (float) $r['percent']);
        }
        $this->echoJson(array(
            'a' => $r1
        ));
    }

}
